package org.huang.user.consumer.handler;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.huang.user.consumer.util.JSONUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

@Aspect
@Component
@Order(-100)
@Slf4j(topic = "webLog")
public class WebLogAspect {

    @Pointcut("execution(public * org.huang.user.consumer.controller.*.*(..))") //两个..代表所有子目录，最后括号里的两个..代表所有参数
    public void logPointCut() {
    }

    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.debug("* Server has received a request on thread {}", Thread.currentThread().getName());
        log.debug("*{}> {} {}", new Object[] { Thread.currentThread().getName(), request.getMethod(),
                request.getRequestURL().toString() });
        log.debug("*{}> mediaType => {}", Thread.currentThread().getName(),
                request.getContentType() == null ? "null" : request.getContentType());
        log.debug("*{}> RemoteIP => {}", Thread.currentThread().getName(), request.getRemoteAddr());
        log.debug("*{}> classMethod => {}", Thread.currentThread().getName(),
                pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());
        String param = Arrays.toString(pjp.getArgs()).replaceAll("\"image\":\"([^\"]+\")", "\"image\":\"******\"");

        log.debug("*{}> Params => {}", Thread.currentThread().getName(), param);
        long startTime = System.currentTimeMillis();
        // ob 为方法的返回值
        Object ob = pjp.proceed();
        // 处理完请求，返回内容
        HttpServletResponse response = attributes.getResponse();
        log.debug("* Server has Server responded with a response on thread {}", Thread.currentThread().getName());
        log.debug("*{}< status: {}", Thread.currentThread().getName(), response.getStatus());
        log.debug("*{}< mediaType => {}", Thread.currentThread().getName(),
                response.getContentType() == null ? "null" : response.getContentType());
        log.debug("*{}< response => {}", Thread.currentThread().getName(), JSONUtils.toJson(ob));
        log.debug("*{}< take time : {}ms", Thread.currentThread().getName(), System.currentTimeMillis() - startTime);
        return ob;
    }

}
